"""
HTTP client for interacting with a remote registration service.
"""

from __future__ import annotations

from pathlib import Path
from typing import Any, Dict, Optional

import requests

from services.registration_parser import parse_registration_result


class RegistrationAPIClient:
    """Simple wrapper around the remote registration REST API."""

    def __init__(self, base_url: str) -> None:
        self.base_url = base_url.rstrip("/")

    def register_point_clouds(
        self,
        source_ply: Path | str,
        target_ply: Path | str,
        *,
        is_small_cloud: Optional[bool] = None,
        max_attempts: Optional[int] = None,
        random_seed: Optional[int] = None,
        timeout_seconds: int = 600,
    ) -> Dict[str, Any]:
        """
        Submit a registration job to the remote API.

        Returns:
            Parsed response dictionary containing status, transform_matrix and metrics.
        """
        url = f"{self.base_url}/register/"
        payload = {}
        if is_small_cloud is not None:
            payload["is_small_cloud"] = is_small_cloud
        if max_attempts is not None:
            payload["max_attempts"] = max_attempts
        if random_seed is not None:
            payload["random_seed"] = random_seed

        with open(source_ply, "rb") as src_file, open(target_ply, "rb") as tgt_file:
            files = {
                "source_ply": src_file,
                "target_ply": tgt_file,
            }
            response = requests.post(url, files=files, data=payload, timeout=timeout_seconds)
            response.raise_for_status()

        return parse_registration_result(response.json())


